from rest_framework import serializers
from . import models
from hippo_api.utils.handle_key import AppSetting
from hippo_api.utils.check_host import valid_ssh
from hippo_api.libs.ssh import SSH


class HostCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.HostCategory
        fields = ['id', 'name']



class HostModelSerializer(serializers.ModelSerializer):
    category_name = serializers.CharField(source='category.name', read_only=True)
    password = serializers.CharField(write_only=True)

    # {'category':1, 'hostname':'localhost' ,'iP_addr': '127.0.0.1', 'port':22, desc: 'asdf'}
    class Meta:
        model = models.Host
        fields = ['id', 'category', 'category_name', 'hostname', 'ip_addr', 'port', 'desc', 'username', 'password']
        extra_kwargs = {
            'category': {'write_only': True},
        }

        # 校验用户提交过来的数据是否有能够真实的连接某台主机

    def validate(self, attrs):
        print(attrs)
        ip_addr = attrs.get('ip_addr')
        port = attrs.get('port')
        username = attrs.get('username')
        password = attrs.get('password')

        ret = valid_ssh(ip_addr, port, username, password)
        print(ret)
        if not ret:
            raise serializers.ValidationError('参数校验失败，请检查输入的内容')

        print(attrs)
        return attrs

        # validated_data = {'category':1, 'password':'123', 'hostname':'localhost' ,'iP_addr': '127.0.0.1', 'podt':22, desc: 'asdf'}

        # 数据保存

        # 添加host记录，如果第一次添加host记录，那么需要我们生成全局的公钥和私钥

    def create(self, validated_data):
        print('>>>>>', validated_data)
        ip_addr = validated_data.get('ip_addr')
        port = validated_data.get('port')
        username = validated_data.get('username')
        password = validated_data.get('password')

        # 创建公私钥之前，我们先看看之前是否已经创建过公私钥了
        _cli = SSH(ip_addr, port, username, password=str(password))
        try:
            private_key = AppSetting.get('private_key')
            public_key = AppSetting.get('public_key')
        except KeyError:

            # 如果之前没有创建过，那么就创建公钥和私钥
            private_key, public_key = _cli.generate_key()
        # 将公钥和私钥保存到数据库中
        AppSetting.set('private_key', private_key, 'ssh private key')
        AppSetting.set('public_key', public_key, 'ssh public key')

        # 将公钥上传到服务器上保存

        _cli.add_public_key(public_key)

        # 剔除密码字段，保存host记录
        password = validated_data.pop('password')
        new_host_obj = models.Host.objects.create(
            **validated_data
        )

        return new_host_obj
